package com.qf.homeproject;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.qf.adapter.CityListAdapter;
import com.qf.bean.City;
import com.qf.config.AppConfig;
import com.qf.utils.ChineseToPinyinHelper;
import com.qf.utils.DBhelper;
import com.qf.view.LetterIndexerView;
import com.qf.view.LetterIndexerView.OnLetterClickedListener;

public class IndexActivity extends Activity implements SectionIndexer
{

	TextView textView_Dialog;
	String url;
	ListView lv;
	CityListAdapter adapter;
	List<City> datas;
	EditText et_bar;
	TextView tView;

	DBhelper dbHelper;
	private int lastFirstVisibleItem = -1;
	private LetterIndexerView letterIndexerView_main;
	private RequestQueue queue;
	private TextView titleLayout;
	private TextView letterTv;
	private View views;
	private SQLiteDatabase db;
	private Cursor cursor;
	private SQLiteDatabase dbs;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{

		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE); // 对标题栏进行隐藏
		setContentView(R.layout.activity_index);
		titleLayout = (TextView) findViewById(R.id.tvId_xuanfu);
		views = LayoutInflater.from(this).inflate(R.layout.item_listview, null);

		initDatabase();
		init();
		getCityListDatas();

		initet_barEvent();

		// initScrollSuspend();

	}

	/**
	 * 根据EditText输入的内容查询结果
	 */
	private void initet_barEvent()
	{
		et_bar.addTextChangedListener(new TextWatcher()
		{

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count)
			{
				datas.clear();
				getCityListDatas();
				filterData(s.toString());
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after)
			{
			}

			@Override
			public void afterTextChanged(Editable s)
			{
			}
		});
	}

	/**
	 * 根据输入的内容对数据进行过滤
	 */
	private void filterData(String keyWords)
	{
		List<City> filterDateList = new ArrayList<City>();

		// 如果输入的为空,则显示原来的数据
		if (TextUtils.isEmpty(keyWords))
		{
			filterDateList.addAll(datas);
		}
		else
		{
			filterDateList.clear();
			for (City City : datas)
			{
				String name = City.getCityName();
				if (name.toUpperCase().indexOf(
						keyWords.toString().toUpperCase()) != -1
						|| ChineseToPinyinHelper.getInstance().getPinyin(name)
								.startsWith(keyWords.toString()))
				{
					filterDateList.add(City);
				}
			}
		}

		// 每次数据源跟=更新之后，将i该为零，让listView每次滑动的时候重新从数据库获取数据源
		i = 0;

		adapter.reLoadListView(filterDateList, true);

	}

	private void initDatabase()
	{
		dbHelper = new DBhelper(this);
		db = dbHelper.getWritableDatabase();
	}

	/**
	 * 实现对下载下来的数据进行本地数据库的保存
	 */
	private void getCityListDatas()
	{
		dbs = dbHelper.getWritableDatabase();
		cursor = dbs.query("t_json", new String[] { "json" }, null, null, null,
				null, null);
		// 如果查询不到数据,则从网络加载数据
		if (!cursor.moveToNext())
		{
			getDataFromServer();
		}
		else
		{

			dbs = dbHelper.getReadableDatabase();
			cursor = dbs.query("t_json", new String[] { "json" }, null, null,
					null, null, null);
			cursor.moveToNext();
			String json = cursor.getString(cursor.getColumnIndex("json"));
			try
			{
				parseJSON(json);
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
		}
	}

	@SuppressLint("NewApi")
	private void init()
	{
		url = AppConfig.CHOICE_CITY;
		datas = new ArrayList<City>();
		textView_Dialog = (TextView) findViewById(R.id.showletter_tv);
		lv = (ListView) findViewById(R.id.lvId);

		et_bar = (EditText) findViewById(R.id.edit_search_id);
		letterIndexerView_main = (LetterIndexerView) findViewById(R.id.customid);
		letterIndexerView_main.initTextView(textView_Dialog);
		adapter = new CityListAdapter(this, datas);
		lv.setAdapter(adapter);

		initLetterIndexEvent();
		tofirstPager();

	}

	/**
	 * 从城市列表跳转到首页 同时将cityId给传过去
	 */
	private void tofirstPager()
	{
		lv.setOnItemClickListener(new OnItemClickListener()
		{

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id)
			{
				String cityId = datas.get(position).getCityId();
				String cityName = datas.get(position).getCityName();
				Intent intent = new Intent(IndexActivity.this,
						MainActivity.class);
				Log.i("info", "城市的id为:" + cityId);
				intent.putExtra("cityId", cityId);
				intent.putExtra("cityName", cityName);
				startActivity(intent);
			}
		});
	}

	private void initLetterIndexEvent()
	{
		letterIndexerView_main
				.setOnLetterClickedListener(new OnLetterClickedListener()
				{

					@Override
					public void onLetterClicked(String letter) // 传过来一个字母
					{
						int positon = adapter.getPositionForSection(letter
								.charAt(0));
						lv.setSelection(positon);
					}
				});
	}

	/**
	 * 开启一个子线程下载并解析网络数据
	 */
	public void getDataFromServer()
	{
		queue = Volley.newRequestQueue(this);
		StringRequest request = new StringRequest(url, new Listener<String>()
		{

			@Override
			public void onResponse(String response)
			{
				try
				{
					ContentValues values = new ContentValues();
					values.put("json", response);
					Long count = db.insert("t_json", null, values);
					parseJSON(response);

				}
				catch (Exception e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}, new ErrorListener()
		{

			@Override
			public void onErrorResponse(VolleyError error)
			{
			}
		});
		// 将请求加到请求队列中，执行子线程的下载
		queue.add(request);

	}

	// 对下载下来的数据进行解析
	public void parseJSON(String json) throws Exception
	{

		String key[] = { "hotcities", "A", "B", "C", "D", "E", "F", "G", "H",
				"J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "W", "X",
				"Y", "Z" };

		JSONObject object = new JSONObject(json); //
		JSONObject obj = object.getJSONObject("cities");
		for (int i = 0; i < obj.length(); i++)
		{
			JSONArray array = obj.getJSONArray(key[i]);
			adapter.reLoadListView(jsonArray(array), false);
		}

	}

	public List<City> jsonArray(JSONArray array) throws Exception
	{
		List<City> cList = new ArrayList<City>();
		City city = null;
		for (int i = 0; i < array.length(); i++)
		{
			city = new City();
			String cityName = array.getJSONObject(i).getString("cityname");
			String cityId = array.getJSONObject(i).getString("cityid");
			String cityPinYin = array.getJSONObject(i).getString("citypinyin");

			String firstLetter = cityPinYin.substring(0, 1).toUpperCase();

			city.setCityName(cityName);
			city.setCityId(cityId);
			if (firstLetter.matches("[A-Z]"))
			{
				city.setFirstLetter(firstLetter);
			}
			else
			{
				city.setFirstLetter("#");
			}

			cList.add(city);
		}

		return cList;
	}

	/**
	 * 点击取消按钮的时候，IndexActivity销毁
	 * 
	 * @param view
	 */
	public void dismiss(View view)
	{
		finish();
	}

	/**
	 * listView实现分组悬浮的效果
	 * 
	 */

	int i = 0;

	private void initScrollSuspend()
	{

		lv.setOnScrollListener(new OnScrollListener()
		{

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState)
			{
			}

			// 实现分组悬浮和压缩的效果
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount)
			{

				if (i == 0)
				{
					datas.clear();
					getCityListDatas();
				}
				i++;
				int section = getSectionForPosition(firstVisibleItem);
				int nextSection = getSectionForPosition(firstVisibleItem + 1);
				int nextSecPosition = getPositionForSection(nextSection);
				if (firstVisibleItem != lastFirstVisibleItem)
				{

					ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) titleLayout
							.getLayoutParams();
					params.topMargin = 0;
					titleLayout.setLayoutParams(params);

					if (firstVisibleItem >= 4)
					{
						titleLayout.setText(datas
								.get(getPositionForSection(section))
								.getFirstLetter().charAt(0)
								+ "");
					}

					if (firstVisibleItem < 4)
					{
						titleLayout.setText("热门城市");
					}
				}

				if (firstVisibleItem >= 2)
				{
					if (nextSecPosition == firstVisibleItem + 1)
					{
						View childView = view.getChildAt(0);
						if (childView != null)
						{
							int titleHeight = titleLayout.getHeight();
							int bottom = childView.getBottom();
							ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) titleLayout
									.getLayoutParams();

							if (bottom < titleHeight)
							{
								// 移动的距离为负数
								float pushedDistance = bottom - titleHeight;
								params.topMargin = (int) pushedDistance;
								titleLayout.setLayoutParams(params);
							}
							else
							{
								if (params.topMargin != 0)
								{
									params.topMargin = 0;
									titleLayout.setLayoutParams(params);
								}
							}
						}
					}
					lastFirstVisibleItem = firstVisibleItem;
				}

			}

		});
	}

	@Override
	public Object[] getSections()
	{
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int getPositionForSection(int sectionIndex)
	{
		for (int i = 4; i < datas.size(); i++)
		{
			String firstLetter = datas.get(i).getFirstLetter();
			int firstChar = firstLetter.charAt(0);
			if (firstChar == sectionIndex) { return i; }
		}
		return -1;
	}

	@Override
	public int getSectionForPosition(int position)
	{

		return datas.get(position).getFirstLetter().charAt(0);

	}

	/**
	 * 最后进行资源的释放
	 */
	@Override
	protected void onDestroy()
	{
		super.onDestroy();
		if (queue != null)
		{
			queue.stop();
		}
	}

}
